import 'package:flutter/material.dart';
import 'package:core_package/core_package.dart';
import 'package:flutter_app_unionad/event_or_delegate/reload_event.dart';
import 'package:flutter_app_unionad/model/GetFirstInviteListItem.dart';
import 'package:flutter_app_unionad/request/promotion_request.dart';
import 'package:flutter_app_unionad/view_model/change_device_event.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

class TeamSellWidget extends StatefulWidget {
  final bool isTeam;

  const TeamSellWidget({Key? key, this.isTeam = false}) : super(key: key);

  @override
  _TeamSellWidgetState createState() => _TeamSellWidgetState();
}

class _TeamSellWidgetState extends State<TeamSellWidget> with AutomaticKeepAliveClientMixin {
  int page = 0;
  EasyRefreshController? _controller;
  List<GetFirstInviteListItem>? dataSource;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller = EasyRefreshController();
    getData();
  }

  void getData() {
    page = 1;
    PromotionRequest.getFirstInviteList(pageNum: page, type: widget.isTeam ? 0 : 1).then((value) {
      if (dataSource == null) dataSource = [];
      dataSource?.clear();
      dataSource?.addAll(value);

      if (mounted) setState(() {});
    });
  }

  void getMoreData() {
    page++;
    PromotionRequest.getFirstInviteList(pageNum: page, type: widget.isTeam ? 0 : 1).then((value) {
      if (dataSource == null) dataSource = [];
      dataSource?.addAll(value);

      if (dataSource != null && dataSource!.length < 20) {
        _controller!.finishLoadCallBack?.call();
      } else {
        _controller!.resetLoadStateCallBack?.call();
      }
      if (mounted) setState(() {});
    });
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        MySizeBox(height: 25.px),
        buildTitleWidget(),
        MySizeBox(height: 5),
        buildListWidget(),
        MySizeBox(height: 5),
      ],
    );
  }

  Widget buildListWidget() {
    return Expanded(
      child: buildListContent(),
    );
  }

  Widget buildListContent() {
    if (dataSource == null) {
      return ProgressDialog.showFirstLoading();
    }
    if (dataSource!.length == 0) {
      return Center(child: EmptyWidget());
    }
    return EasyRefresh(
      header: RefreshBasics.header,
      footer: RefreshBasics.footer,
      controller: _controller,
      onRefresh: () async {
        eventBus.fire(TabViewReloadDataEvent(index: 1));

        getData();
      },
      onLoad: () async {
        getMoreData();
      },
      child: ListView.builder(
        padding: EdgeInsets.zero,
        itemCount: dataSource!.length,
        itemBuilder: (ctx, index) {
          String status;
          if (dataSource![index].status == 1) {
            status = '已预约';
          } else if (dataSource![index].status == 2) {
            status = '已激活';
          } else {
            status = '已取消';
          }
          String dateTime = '';
          if (dataSource![index].createTime != null) {
            DateTime dateTime1 = DateTime.fromMillisecondsSinceEpoch(dataSource![index].createTime);
            dateTime = '${dateTime1.year}-${dateTime1.month}-${dateTime1.day}';
          }
          return buildListItemWidget(
              dataSource![index].createTime == null ? '' : dateTime,
              dataSource![index].mobile!.replaceRange(3, 7, ' **** '),
              status,
              dataSource![index].points == null ? '' : dataSource![index].points.toString(),
              dataSource![index].level == 2);
        },
      ),
    );
  }

  Widget buildListItemWidget(String date, String type, String status, String number, bool isTeam) {
    return Container(
      child: Stack(
        children: [
          Padding(
            padding: EdgeInsets.symmetric(vertical: 8.px),
            child: Row(
              children: [
                buildItemTextWidget(date),
                buildItemTextWidget(type),
                buildItemTextWidget(status),
                buildItemTextWidget(number),
              ],
            ),
          ),
          if (isTeam)
            Positioned(
                top: 0,
                right: 10,
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 2.px),
                  decoration: BoxDecoration(
                    color: Colors.redAccent,
                    border: Border.all(color: Colors.redAccent),
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: Text(
                    '团',
                    style: TextStyle(
                      fontSize: 8.px,
                      color: Colors.white,
                    ),
                  ),
                ))
        ],
      ),
    );
  }

  Widget buildItemTextWidget(String string) {
    return Container(
      alignment: Alignment.center,
      width: SizeFill.screenWidth! / 4 - 5.px,
      child: Text(
        string,
        style: TextStyle(
          color: MyColors.color_27_27_27,
          fontWeight: MyFontWeight.regular,
          fontSize: MyFont.font12,
        ),
      ),
    );
  }

  Widget buildTitleWidget() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        buildTitleItemWidget("日期", () {}),
        buildTitleItemWidget("用户", () {}),
        buildTitleItemWidget("推广进度", () {}),
        buildTitleItemWidget("金币数量", () {}),
      ],
    );
  }

  Widget buildTitleItemWidget(String title, Function() onTap) {
    return Container(
      width: SizeFill.screenWidth! / 4 - 5.px,
      alignment: Alignment.center,
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            title,
            style: TextStyle(
              color: MyColors.color_27_27_27,
              fontSize: MyFont.font13,
              fontWeight: MyFontWeight.regular,
            ),
          ),
          SizedBox(width: 2),
          Icon(
            Icons.arrow_drop_down,
            size: 15.px,
            color: MyColors.color_27_27_27,
          ),
        ],
      ),
    );
  }
}
